/*
 *    Copyright 2016-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package nullability.test

import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.jvm.K2JVMCompiler
import org.jetbrains.kotlin.config.Services
import java.io.File

/**
 * Compiles the source lines and returns any error reports generated by the compiler.
 */
fun compile(source: String): CompilerErrorMessageCollector {
    val file: File = File.createTempFile("KotlinTest", ".kt")
    file.deleteOnExit()
    // normalize line endings and write to temp file
    file.writeText(source.trimIndent().lines().joinToString(separator = System.lineSeparator()))

    val compilerArgs = K2JVMCompilerArguments().apply {
        freeArgs = listOf(file.path)
        destination = System.getProperty("java.io.tmpdir")
        classpath = System.getProperty("java.class.path")
        noStdlib = true
    }

    return CompilerErrorMessageCollector().apply {
        K2JVMCompiler().exec(this, Services.EMPTY, compilerArgs)
    }
}

class CompilerErrorMessageCollector: MessageCollector {
    val reports = mutableListOf<CompilerErrorReport>()
     override fun clear() = reports.clear()

    override fun hasErrors() = reports.any { it.severity.isError }

    override fun report(
        severity: CompilerMessageSeverity,
        message: String,
        location: CompilerMessageSourceLocation?
    ) {
        reports.add(CompilerErrorReport(severity, message, location))
    }

    fun errorLocations() =
        reports.filter { it.severity.isError }
            .mapNotNull { it.location }
            .map { ErrorLocation(it.line, it.column) }
}

data class CompilerErrorReport(
    val severity: CompilerMessageSeverity,
    val message: String,
    val location: CompilerMessageSourceLocation?
)
data class ErrorLocation(val line: Int, val column: Int)
